<template>
  <login-container>
    <UPButton
      @onClick="register"
      :scope="scope"
      style="width: 100%; height: 100%; background-color: #fd7206"
    >
      立即支付
    </UPButton>
  </login-container>
</template>
<script lang="ts" setup>
import type {
  UnionPayLoginData,
  UnionPayRegisterData,
  UnionPayLoginResponse
} from "@/api/unionpay/types";

import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStoreHook } from "@/stores/modules/user";
import { storageUtil } from "@/utils/storage";
import { loadSDK } from "@/utils/loadSDK";

import LoginContainer from "@/components/LoginContainer/index.vue";

const route = useRoute();
const router = useRouter();
const userStore = useUserStoreHook();

const scope = ref("scope.mobile");

onMounted(async () => {
  await loadSDK.unionSDK();
  getCode().then((res: any) => {
    unionpayLogin(res.code);
  });
});

// 静默授权
const getCode = () => {
  return new Promise((resolve, reject) => {
    window.upsdk.appletAuth({
      success: (res: any) => {
        resolve(res);
      },
      fail: () => {
        reject("登录失败");
      }
    });
  });
};

//静默登录
function unionpayLogin(code: string) {
  userStore
    .unionpayLogin({
      requestId: Math.random() * 10 + "",
      code: code
    } as UnionPayLoginData)
    .then((res: UnionPayLoginResponse) => {
      if (res.status) {
        let redirect = storageUtil.queryRedirect(route);
        router.push(redirect);
      } else {
        console.log("静默登录失败" + res.message);
      }
    });
}

//注册登录
const register = (event: any, err: any, result: any) => {
  console.log(event, err, result);
  console.log(result.code);
  console.log(result.code);
  userStore
    .unionpayRegister({
      requestId: Math.random() * 10 + "",
      code: result.code
    } as UnionPayRegisterData)
    .then((res: UnionPayLoginResponse) => {
      if (res.status) {
        console.log("登录成功");
        let redirect = storageUtil.queryRedirect(route);
        router.push(redirect);
      } else {
        console.log("注册登录失败" + res.message);
      }
    });
};
</script>
